15 - Introduction to R
Plot kWh per square foot by year for the following University of Georgia data. Before starting, read the boxed insert in the book on smart editing.
| Year | Square Feet | kWh |
|---|---|---|
| 2007 | 14,214,216 | 2,141,705 |
| 2008 | 14,359,041 | 2,108,088 |
| 2009 | 14,752,886 | 2,150,841 |
| 2010 | 15,341,886 | 2,211,414 |
| 2011 | 15,573,100 | 2,187,164 |
| 2012 | 15,740,742 | 2,057,364 |
year <- c(2007, 2008, 2009, 2010, 2011, 2012)
sqfeet <- c(14214216, 14359041, 14752886, 15341886, 15573100, 15740742)
kwh <- c(2141705, 2108088, 2150841, 2211414, 2187164, 2057364)
kwhpersqft <- kwh/sqfeet
plot(year,kwhpersqft)Create a matrix with 6 rows and 3 columns containing the numbers 1 through 18.
m <- matrix(118, nrow=6,ncol=3)Install the measurement package and use one of its functions to do the following conversions
- 100ºF to ºC
- 100 meters to feet
library(measurement)
conv_unit(100,'F','C')
conv_unit(100,'m','ft')Install the measurement package and run the preceding code.
# Create a new column with the temperature in Celsius
library(measurement)
url <- "http//people.terry.uga.edu/rwatson/data/centralparktemps.txt"
t <- read.table(url, header=T, sep=',')
# compute Celsius
t$Ctemp = round(conv_unit(t$temperature,'F','C'),1)View the web page of yearly CO2 emissions (million metric tons) since the beginning of the industrial revolution
Create a new text file using R
Clean up the file for use with R and save it as CO2.txt
Import (Import Dataset) the file into R
Plot year versus CO2 emissions
Select all the data on the page and copy it.
In RStudio
- File > New File > Text File
- Paste the data
- Remove descriptive information
- Edit headings so they occupy a single row (e.g., Cement_Production)
- Remove any remaining blank rows
- Save the file as CO2.txt
- Import Dataset > From Local File > CO2.txt
- plot(CO2$Year,CO2$Total)
- Save the file for future use
- write_csv(CO2,“CO2_yearly_emissions.csv”)
The saved file is available.
Using the Atlanta weather database and the lubridate package, compute the average temperature at 5 pm in August.
Determine the maximum temperature for each day in August across all years in the input file.
library(dplyr)
library(lubridate)
library(DBI)
conn <- dbConnect(RMySQLMySQL(), "richardtwatson.com", dbname="Weather", user="db2", password="student")
# Query the database and create file t for use with R
t <- dbGetQuery(conn,"select * from record;`")
t$year <- year(t$timestamp)
t$month <- month(t$timestamp)
t$hour <- hour(t$timestamp)
head(t)# Compute the average temperature at 5pm in August
t %>% filter(hour==17 & month==8) %>% summarize(mean=mean(airTemp))# Compute the maximum temperature for each day in August
t$day <- day(t$timestamp)
t %>% filter(month==8) %>% group_by(day) %>% summarize(max=max(airTemp))